<template>
  <div class="common-layout">
    <el-container class="box">
      <!-- 左侧菜单栏 -->
      <el-aside class="el-aside" :width="isCollapse ? '64px' : '200px'">
        <div class="logo-container" @click="toggleCollapse">
          <el-icon class="logo-icon"><OfficeBuilding /></el-icon>
          <div class="logo-text" v-show="!isCollapse">物业管理系统</div>
        </div>
        <el-menu
          active-text-color="#409EFF"
          background-color="#1f2d3d"
          class="el-menu-vertical-demo"
          default-active="2"
          text-color="#fff"
          :router="true"
          :collapse="isCollapse"
        >
          <template v-for="item in filteredMenu">
            <!-- 两级菜单 -->
            <template v-if="item.subs">
              <el-sub-menu :index="item.title" :key="item.title">
                <!-- 一级菜单标题 -->
                <template #title>
                  <el-icon class="menu-icon"><component :is="item.icon || 'Document'" /></el-icon>
                  <span class="menu-title">{{ item.title }}</span>
                </template>
                <!-- 二级菜单标题 -->
                <template v-for="subItem in item.subs" :key="subItem.index">
                  <!-- 三级菜单 -->
                  <template v-if="subItem.subs">
                    <el-sub-menu :index="subItem.title">
                      <template #title>{{ subItem.title }}</template>
                      <template v-for="thirdItem in subItem.subs" :key="thirdItem.index">
                        <el-menu-item
                          :index="thirdItem.index"
                          @click="() => handleMenuItem(thirdItem)"
                        >{{ thirdItem.title }}</el-menu-item>
                      </template>
                    </el-sub-menu>
                  </template>
                  <!-- 二级菜单项 -->
                  <template v-else>
                    <el-menu-item
                      :index="subItem.index"
                      @click="() => handleMenuItem(subItem)"
                    >{{ subItem.title }}</el-menu-item>
                  </template>
                </template>
              </el-sub-menu>
            </template>

            <!-- 一级菜单 -->
            <template v-else>
              <el-menu-item
                :index="item.index"
                :key="item.title"
                @click="() => handleMenuItem(item)"
              >
                <el-icon class="menu-icon"><component :is="item.icon || 'Document'" /></el-icon>
                <span class="menu-title">{{ item.title }}</span>
              </el-menu-item>
            </template>
          </template>
        </el-menu>
        
        <!-- 收缩按钮 -->
        <div class="collapse-btn" @click="toggleCollapse">
          <el-icon v-if="isCollapse"><Expand /></el-icon>
          <el-icon v-else><Fold /></el-icon>
        </div>
      </el-aside>

      <el-container>
        <!-- header头部菜单 -->
        <el-header class="header">
          <div class="header-left">
            <div class="today-info">
              <el-icon><Calendar /></el-icon>
              <span>今日: {{ todayDate }} {{ dayOfWeek }}</span>
              <span class="weather-info" v-if="weather">{{ weather }}</span>
            </div>
          </div>
          <div class="header-right">
            <div class="workspace-btn">
              <el-button type="primary" plain>
                <el-icon><Monitor /></el-icon>
                <span>我的工作台</span>
              </el-button>
            </div>
            <el-dropdown trigger="click">
              <div class="user-info">
                <div class="avatar">
                  <img src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" alt="用户头像">
                </div>
                <span>{{ username || '未登录' }}</span>
                <el-icon><arrow-down /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>我的消息</el-dropdown-item>
                  <el-dropdown-item @click="exitLogin">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>

        <!-- 主体模块：标签页 + 当前路由内容 -->
        <el-main class="el-main">
          <el-tabs
            type="border-card"
            v-model="activeTabName"
            class="main-tabs"
            @tab-remove="handleRemove"
            @tab-click="handleSwitchRoute"
          >
            <el-tab-pane
              v-for="item in editableTabs"
              :key="item.index"
              :label="item.title"
              :name="item.index"
              :closable="handleisClose(item)"
            >
              <router-view />
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  HomeFilled,
  Management,
  OfficeBuilding,
  Promotion,
  Service,
  User,
  Tools,
  Loading,
  ArrowDown,
  Calendar,
  Expand,
  Fold,
  Monitor
} from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: "MainLayout",
  mounted() {
    // 获取用户名
    this.username = localStorage.getItem('username') || 'Admin';
    // 获取用户角色
    this.userRole = localStorage.getItem('userRole') || 'ROLE_ADMIN';
    console.log('当前用户角色:', this.userRole); // 添加调试信息
    
    // 输出权限信息用于调试
    const permissionsStr = localStorage.getItem('permissions');
    const userRolesStr = localStorage.getItem('userRoles');
    console.log('localStorage中的权限:', permissionsStr ? JSON.parse(permissionsStr) : '无');
    console.log('localStorage中的角色:', userRolesStr ? JSON.parse(userRolesStr) : '无');
    
    // 设置今日日期
    this.updateTodayInfo();
  },
  data() {
    return {
      username: '',
      isCollapse: false,
      todayDate: '',
      dayOfWeek: '',
      weather: '晴朗 26°C',
      //当前选项卡
      activeTabName: "home",
      //需要显示的标签数组
      editableTabs: [
        {
          title: "首页",
          index: "home",
        },
      ],
      //左侧菜单选项配置
      asideMenu: [
       
        {
          title: "小区管理",
          icon: "Management",
          permission: "VIEW_COMMUNITY",
          subs: [
            {
              title: "小区列表",
              index: "property/community",
              permission: "VIEW_COMMUNITY"
            }
          ],
        },
        {
          title: "房产管理",
          icon: "OfficeBuilding",
          permission: "VIEW_BUILDING",
          subs: [
            {
              title: "栋数管理",
              index: "property/building",
              permission: "VIEW_BUILDING"
            },
            {
              title: "房产列表",
              index: "property/home",
              permission: "VIEW_HOUSE"
            }
          ],
        },
         {
          title: "人员管理",
          icon: "User",
          permission: "VIEW_OWNER",
          subs: [
            {
              title: "业主管理",
              index: "property/personnel/owner",
              permission: "VIEW_OWNER"
            },
            {
              title: "车辆管理",
              index: "property/personnel/vehicle",
              permission: "VIEW_VEHICLE"
            }
          ],
        },
        {
          title: "车位管理",
          icon: "Promotion",
          permission: "VIEW_PARKING",
          subs: [
            {
              title: "车位管理",
              index: "property/parking",
              permission: "VIEW_PARKING"
            },
            {
              title: "使用记录",
              index: "property/parking/usage",
              permission: "VIEW_PARKING_USAGE"
            }
          ],
        },
        {
          title: "服务管理",
          icon: "Service",
          permission: "VIEW_SERVICE",
          subs: [
            {
              title: "活动管理",
              index: "property/service/activity",
              permission: "VIEW_ACTIVITY"
            },
            {
              title: "报修管理",
              index: "property/service/repair",
              permission: "VIEW_REPAIR"
            },
            {
              title: "投诉管理",
              index: "property/service/complaint",
              permission: "VIEW_COMPLAINT"
            },
            {
              title: "信箱管理",
              index: "property/service/mailbox",
              permission: "VIEW_MAILBOX"
            }
          ],
        },
        {
          title: "系统管理",
          icon: "Setting",
          permission: "VIEW_SYSTEM_DASHBOARD",
          subs: [
            {
              title: "用户管理",
              index: "system/user",
              permission: "MANAGE_USERS"
            },
            {
              title: "角色管理",
              index: "system/role",
              permission: "MANAGE_ROLES"
            },
            {
              title: "权限管理",
              index: "system/permission",
              permission: "MANAGE_PERMISSIONS"
            }
          ],
        },
      ],
      userRole: 'ROLE_ADMIN', // 修改默认角色
      dataLoading: false
    };
  },
  components: {
    Document,
    IconMenu,
    Location,
    Setting,
    HomeFilled,
    Management,
    OfficeBuilding,
    Promotion,
    Service,
    User,
    Tools,
    Loading,
    ArrowDown,
    Calendar,
    Expand,
    Fold,
    Monitor
  },
  watch: {
    activeTabName: function () {
      console.log("高亮的index值", this.activeTabName);
    },
  },
  computed: {
    // 根据用户角色过滤菜单
    filteredMenu() {
      // 获取用户权限
      const permissionsStr = localStorage.getItem('permissions');
      const userRolesStr = localStorage.getItem('userRoles');
      
      if (!permissionsStr) {
        console.warn('未找到权限数据');
        return [];
      }
      
      // 解析权限列表和角色列表
      const permissions = JSON.parse(permissionsStr);
      const userRoles = userRolesStr ? JSON.parse(userRolesStr) : [];
      
      console.log('当前用户角色:', userRoles);
      console.log('当前用户权限:', permissions);
      
      // 过滤一级菜单
      return this.asideMenu.filter(menu => {
        // 检查菜单是否有权限代码
        if (menu.permission && !this.hasPermission(menu.permission, permissions)) {
          return false;
        }
        
        // 如果有子菜单，过滤子菜单
        if (menu.subs) {
          const filteredSubs = menu.subs.filter(subMenu => {
            // 检查子菜单是否有权限代码
            if (subMenu.permission && !this.hasPermission(subMenu.permission, permissions)) {
              return false;
            }
            
            // 如果有三级菜单，过滤三级菜单
            if (subMenu.subs) {
              const filteredThirdSubs = subMenu.subs.filter(thirdMenu => {
                return !thirdMenu.permission || this.hasPermission(thirdMenu.permission, permissions);
              });
              
              // 更新三级菜单
              subMenu.subs = filteredThirdSubs;
              
              // 如果没有三级菜单，则不显示该二级菜单
              return filteredThirdSubs.length > 0;
            }
            
            return true;
          });
          
          // 更新二级菜单
          menu.subs = filteredSubs;
          
          // 如果没有二级菜单，则不显示该一级菜单
          return filteredSubs.length > 0;
        }
        
        return true;
      });
    }
  },
  methods: {
    // 切换侧边栏折叠状态
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    
    // 更新今日信息
    updateTodayInfo() {
      const today = new Date();
      const year = today.getFullYear();
      const month = today.getMonth() + 1;
      const day = today.getDate();
      this.todayDate = `${year}年${month}月${day}日`;
      
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      this.dayOfWeek = weekdays[today.getDay()];
    },
    
    //处理菜单点击
    handleMenuItem(item) {
      // 如果点击的菜单项不在已打开的标签页中，则添加
      const isExist = this.editableTabs.some((tab) => tab.index === item.index);
      if (!isExist) {
        this.editableTabs.push({
          title: item.title,
          index: item.index,
        });
      }
      // 设置当前活动标签页
      this.activeTabName = item.index;
      
      // 添加路由导航
      this.$router.push('/' + item.index);
    },

    //处理标签页删除
    handleRemove(targetName) {
      // 如果关闭的是当前活动标签页，则需要激活其他标签页
      if (this.activeTabName === targetName) {
        // 找到关闭的标签页在数组中的位置
        const tabs = this.editableTabs;
        let activeIndex = 0;
        for (let i = 0; i < tabs.length; i++) {
          if (tabs[i].index === targetName) {
            activeIndex = i;
            break;
          }
        }

        // 设置新的活动标签页
        if (activeIndex === 0) {
          // 如果关闭的是第一个标签页，则激活下一个
          this.activeTabName = tabs[1].index;
        } else {
          // 否则激活前一个
          this.activeTabName = tabs[activeIndex - 1].index;
        }

        // 路由跳转到新的活动标签页
        this.$router.push(this.activeTabName);
      }

      // 从数组中移除关闭的标签页
      this.editableTabs = this.editableTabs.filter(
        (tab) => tab.index !== targetName
      );
    },

    //判断是否可以关闭标签页（首页不能关闭）
    handleisClose(item) {
      return item.index !== "home";
    },

    //处理标签页切换
    handleSwitchRoute(tab) {
      // 确保路由导航正确
      this.$router.push('/' + tab.props.name);
    },

    //退出登录
    exitLogin() {
      ElMessageBox.confirm("确定要退出登录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 清除登录状态和token
          localStorage.removeItem("token");
          localStorage.removeItem("username");
          localStorage.removeItem("isLogin");
          localStorage.removeItem("userRole"); // 清除用户角色信息
          
          // 跳转到登录页
          this.$router.push("/login");
        })
        .catch(() => {
          // 取消退出
        });
    },

    // 加载测试数据
    loadTestData() {
      this.dataLoading = true;
      
      const token = localStorage.getItem('token');
      const headers = { Authorization: `Bearer ${token}` };
      
      axios.get('/api/init/load-test-data', { headers })
        .then(response => {
          ElMessage.success('测试数据加载成功');
        })
        .catch(error => {
          console.error('加载测试数据失败:', error);
          ElMessage.error('加载测试数据失败: ' + (error.response?.data?.message || error.message));
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    
    // 检查是否有权限
    hasPermission(permission, permissions) {
      if (!permission || !permissions) {
        return true;
      }
      
      // 如果是admin用户，直接返回true
      const userRoles = JSON.parse(localStorage.getItem('userRoles') || '[]');
      if (userRoles.includes('ROLE_ADMIN')) {
        return true;
      }
      
      // 检查权限数组中是否包含该权限
      if (permissions.includes(permission)) {
        console.log(`权限匹配成功: ${permission}`);
        return true;
      }
      
      // 检查通配符权限
      for (const p of permissions) {
        if (p.endsWith('*')) {
          const prefix = p.slice(0, -1);
          if (permission.startsWith(prefix)) {
            console.log(`通配符权限匹配成功: ${permission} 匹配 ${p}`);
            return true;
          }
        }
      }
      
      console.log(`权限检查失败: ${permission}`);
      return false;
    },
  },
};
</script>

<style scoped>
/* 整体布局样式 */
.common-layout {
  font-size: 16px;
  font-family: "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
}

.box {
  width: 100vw;
  height: 100vh;
}

/* 左侧导航样式 */
.el-aside {
  background: #1f2d3d;
  transition: width 0.3s;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  overflow-x: hidden;
  overflow-y: auto;
  position: relative;
  /* 隐藏滚动条但保留滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏WebKit浏览器的滚动条 */
.el-aside::-webkit-scrollbar {
  display: none;
}

.logo-container {
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  background-color: #1a2634;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.logo-icon {
  font-size: 28px;
  color: #409EFF;
  margin-right: 8px;
}

.logo-text {
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  white-space: nowrap;
  transition: opacity 0.3s;
}

.menu-icon {
  font-size: 16px;
  margin-right: 6px;
}

.menu-title {
  font-size: 18px;
  font-weight: 500;
}

.el-menu-vertical-demo {
  border-right: none;
}

.el-menu-vertical-demo .el-sub-menu__title {
  font-size: 18px;
  height: 50px;
  line-height: 50px;
}

.el-menu-vertical-demo .el-menu-item {
  font-size: 17px;
  height: 45px;
  line-height: 45px;
}

/* 收缩按钮样式 */
.collapse-btn {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 40px;
  background-color: #1a2634;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: all 0.3s;
}

.collapse-btn:hover {
  background-color: #409EFF;
}

.collapse-btn .el-icon {
  font-size: 20px;
}

/* 头部导航样式 */
.header {
  background-color: #fff;
  height: 60px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  position: sticky;
  top: 0;
}

.header-left {
  display: flex;
  align-items: center;
}

.today-info {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
}

.today-info .el-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #409EFF;
}

.weather-info {
  margin-left: 15px;
  color: #409EFF;
  font-weight: 500;
  font-size: 16px;
}

.header-right {
  display: flex;
  align-items: center;
}

.workspace-btn {
  margin-right: 20px;
}

.workspace-btn .el-button {
  display: flex;
  align-items: center;
  font-weight: 500;
  padding: 8px 15px;
  border-radius: 8px;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
  background: linear-gradient(135deg, #409EFF 0%, #64b5ff 100%);
  border: none;
  color: white;
}

.workspace-btn .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  background: linear-gradient(135deg, #3a8fe0 0%, #409EFF 100%);
}

.workspace-btn .el-icon {
  margin-right: 6px;
  font-size: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  font-size: 16px;
  padding: 5px 10px;
  border-radius: 20px;
  background-color: #f5f7fa;
  transition: all 0.3s;
  cursor: pointer;
}

.user-info:hover {
  background-color: #ecf5ff;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 8px;
  border: 2px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info span {
  margin-right: 5px;
  font-weight: 500;
}

.user-info .el-icon {
  font-size: 12px;
  color: #909399;
}

/* 主体内容区域样式 */
.el-main {
  background-color: #f5f7fa;
  padding: 0;
}

.main-tabs .el-tabs__header {
  margin-bottom: 0;
  position: sticky;
  top: 60px;
  z-index: 999;
}

.main-tabs .el-tabs__content {
  padding: 20px !important;
  background-color: #fff;
  border-radius: 0 0 4px 4px;
}

.main-tabs .el-tabs__item {
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  font-weight: 500;
}

.main-tabs .el-tabs__item.is-active {
  font-weight: bold;
}
</style>
